
import { InjectRepository } from '@nestjs/typeorm';
import { Repository ,Not ,In,Like} from 'typeorm';
import { Injectable } from '@nestjs/common';
import { ResultData } from 'src/common/utils/result';
import {ProfessionalCourseEntity} from "./entities/professional-course.entity";
import {CreateCourseDto, QueryCourseDto, UpdateCourseDto} from "./dto/profession-course.dto";
import {CourseEntity} from "../course/entities/course.entity";

@Injectable()
export class ProfessionalCourseService {
    constructor(
        @InjectRepository(ProfessionalCourseEntity)
        private readonly professionalCourseEntityRep: Repository<ProfessionalCourseEntity>,
        @InjectRepository(CourseEntity)
        private  readonly courseEntityRep:  Repository<CourseEntity>,
    ) {}

    // 新增方法：批量插入课程
    private async batchInsertCourses(data: Partial<ProfessionalCourseEntity>[]) {
        if (data.length === 0) {
            return;
        }
        await this.professionalCourseEntityRep.manager.transaction(async (transactionalEntityManager) => {
            await transactionalEntityManager
                .createQueryBuilder()
                .insert()
                .into(ProfessionalCourseEntity)
                .values(data)
                .execute();
        });
    }

    async createCourse(createCourseDto: CreateCourseDto) {
        const entity = this.professionalCourseEntityRep.createQueryBuilder('entity');

        // 查询已存在的记录，过滤掉重复的记录
        const existingRecords = await entity
            .where({
                proId: createCourseDto.proId,
                courseId: In(createCourseDto.courseIds) ,
                delFlag:'0'
            })
            .getMany();

        if (existingRecords.length > 0) {
            // 存在的课程ID信息
            const existingIds = existingRecords.map((record) => record.courseId);
            // 不存在的课程ID信息(需新增)
            const newCourseIds = createCourseDto.courseIds.filter((id) => !existingIds.includes(id));
            // 如果存在新的课程ID信息，则进行批量插入
            if (newCourseIds.length > 0) {
                const data = newCourseIds.map((courseId) => ({
                    proId: createCourseDto.proId,
                    courseId,
                    createBy: createCourseDto.createBy,
                    createTime: createCourseDto.createTime,
                }));
                // @ts-ignore
                await this.batchInsertCourses(data); // 调用批量插入方法
                // 查找出已存在的课程名称，组合成字符串，去course表查询，找对应课程名称
                const courseNames = await this.courseEntityRep.find({
                    where: {
                        courseId: In(newCourseIds),
                    },
                    select: ['courseName'],
                })
                let nameStrList = courseNames.map((course) => course.courseName).join(',');
                return ResultData.ok({ message:`新增${newCourseIds.length}条成功,${nameStrList}已存在未添加` });
            } else {
                return ResultData.fail(500, '所有课程ID已存在，无需新增');
            }
        } else {
            // 都是新增数据，批量新增
            const data = createCourseDto.courseIds.map((courseId) => ({
                proId: createCourseDto.proId,
                courseId,
                createBy: createCourseDto.createBy,
                createTime: createCourseDto.createTime,
            }));
            // @ts-ignore
            await this.batchInsertCourses(data); // 调用批量插入方法
            return ResultData.ok({ message: '新增成功' });
        }
    }

    async findAllCourse(query: QueryCourseDto) {
        const entity = this.professionalCourseEntityRep.createQueryBuilder('entity');

        // 关联查询课程表和专业表
        entity.leftJoinAndSelect('entity.course', 'course'); // 确保正确加载 course 关联
        entity.leftJoinAndSelect('entity.professional', 'professional'); // 确保正确加载 professional 关联

        entity.where({ delFlag: '0' });
        if (query.proId) {
            entity.andWhere("entity.proId = :proId", { proId: query.proId });
        }
        if (query.status) {
            entity.andWhere("entity.status = :status", { status: query.status });
        }
        if (query.createBy) {
            entity.andWhere("entity.createBy = :createBy", { createBy: query.createBy });
        }
        if (query.params?.beginTime && query.params?.endTime) {
            entity.andWhere("entity.startDate BETWEEN :start AND :end", { start: query.params.beginTime, end: query.params.endTime });
        }
        if (query.remark) {
            entity.andWhere("entity.remark = :remark", { remark: query.remark });
        }
        if (query.orderByColumn && query.isAsc) {
            const key = query.isAsc === 'ascending' ? 'ASC' : 'DESC';
            entity.orderBy(`entity.${query.orderByColumn}`, key);
        }
        entity.skip(query.pageSize * (query.pageNum - 1)).take(query.pageSize);

        const [list, total] = await entity.getManyAndCount();

        // 映射课程名称和专业名称到结果中
        const resultList = list.map(item => ({
            ...item,
            courseName: item.course?.courseName || '', // 确保从 course 关联中提取 courseName
            professionalName: item.professional?.proName || '', // 确保从 professional 关联中提取 professionalName
        }));
        return ResultData.ok({
            list: resultList,
            total,
        });
    }

    async updateCourse(updateSchoolDto:UpdateCourseDto){
        const entity = this.professionalCourseEntityRep.createQueryBuilder('entity');
        entity.where({ delFlag: '0'});
        // 查找是否已存在 学校ID和专业ID相同的记录(排除自己的记录)，如果存在则不允许添加，返回错误信息
        const existingRecord = await entity.where({ proId: updateSchoolDto.proId, courseId: updateSchoolDto.courseId, id: Not(updateSchoolDto.id) }).getOne();
        if (existingRecord) {
            return ResultData.fail(500, '该学校已开设改专业，请勿重复添加！');
        }
        const res = await this.professionalCourseEntityRep.update({  id: updateSchoolDto.id }, updateSchoolDto);
        return ResultData.ok({value:res.affected >= 1});
    }

    async findOneCourse(id:number){
        const res = await this.professionalCourseEntityRep.findOne({
            where: {
                delFlag: '0',
                id: id,
            },
        });
        return ResultData.ok(res);
    }

    async removeCourse(ids:number[]){
        const res = await this.professionalCourseEntityRep.update(
            { id: In(ids) },
            {
                delFlag: '1',
            },
        );
        return ResultData.ok({value:res.affected >= 1});
    }

}
